import { getUserDetailById, getUserInfo, login } from '@/api/user'
import { getToken, removeToken, setTimeStamp, setToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  updateToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  updateUserInfo(state, newUserInfo) {
    // state.userInfo = newUserInfo
    state.userInfo = { ...newUserInfo } // 浅拷贝
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, data) {
    const res = await login(data)
    // 表示登录接口调用成功 也就是意味着你的用户名和密码是正确的
    // 现在有用户token
    // actions 修改state 必须通过mutations
    context.commit('updateToken', res)
    // 存当下时间戳
    setTimeStamp()
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    const detailRes = await getUserDetailById(res.userId)
    const newRes = { ...res, ...detailRes }
    context.commit('updateUserInfo', newRes)
    return newRes
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
